package org.bizming.medicine.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.bizming.base.service.SqlHelper;
import org.bizming.medicine.model.Medicine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class RemainderMysqlDao implements RemainderDao {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private JdbcTemplate jdbcTemplate;

	private SqlHelper sqlHelper;

	private String tableName = "medicine";

	@Override
	public int count() {
		StringBuilder sb = new StringBuilder();
		sb.append("select count(id) from ").append(getTableName()).append(" where remainder>0");
		String sql = sb.toString();
		logger.info(sql);

		int row = jdbcTemplate.queryForInt(sql);
		return row;
	}

	@Override
	public List<Medicine> selectList() {
		StringBuilder sb = new StringBuilder(
				"select id,commonName,name,jixing,guige,company,approvalNumber,lotNumber,utilDate,unit,remainder  from ");
		sb.append(getTableName()).append(" where remainder>0 limit ?,?");
		String sql = sb.toString();
		logger.info(sql);

		Object[] args = new Object[] { 0, 9999 };

		List<Medicine> rows = jdbcTemplate.query(sql, new MedicineRowMapper(), args);

		sqlHelper.clear(args);

		return rows;
	}

	public List<Medicine> query(String word) {
		StringBuilder sb = new StringBuilder(
				"select id,commonName,name,jixing,guige,company,approvalNumber,lotNumber,utilDate,unit,remainder  from ");
		sb.append(getTableName()).append(" where remainder>0  and commonName='").append(word)
				.append("' limit ?,?");
		String sql = sb.toString();
		logger.info(sql);

		Object[] args = new Object[] { 0, 9999 };

		List<Medicine> rows = jdbcTemplate.query(sql, new MedicineRowMapper(), args);

		sqlHelper.clear(args);

		return rows;
	}

	class MedicineRowMapper implements RowMapper<Medicine> {

		@Override
		public Medicine mapRow(ResultSet rs, int rowNum) throws SQLException {
			Medicine t = new Medicine();
			t.setId(rs.getInt("id"));
			t.setCommonName(rs.getString("commonName"));
			t.setName(rs.getString("name"));
			t.setJixing(rs.getString("jixing"));
			t.setGuige(rs.getString("guige"));
			t.setCompany(rs.getString("company"));
			t.setApprovalNumber(rs.getString("approvalNumber"));
			t.setLotNumber(rs.getString("lotNumber"));
			t.setUtilDate(rs.getLong("utilDate"));
			t.setUnit(rs.getString("unit"));
			t.setRemainder(rs.getInt("remainder"));
			return t;
		}

	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public SqlHelper getSqlHelper() {
		return sqlHelper;
	}

	public void setSqlHelper(SqlHelper sqlHelper) {
		this.sqlHelper = sqlHelper;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}
